package com.jwsoft.manager.core.integration.individuation.impl;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.dygx.QyQueryVO;
import com.jwsoft.manager.common.vo.individuation.HouseHoldSaveVO;
import com.jwsoft.manager.common.vo.individuation.JzzSaveVO;
import com.jwsoft.manager.common.vo.individuation.QySaveVO;
import com.jwsoft.manager.core.dao.model.EduSyncIrs;
import com.jwsoft.manager.core.dao.service.EduSyncIrsService;
import com.jwsoft.manager.core.integration.common.DygxIntegration;
import com.jwsoft.manager.core.integration.individuation.DyIrsSyncIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
@ApiService(funcCode = "IRS330783", title = "东阳发送irs个性化接口")
@Slf4j
public class DyIrsSyncIntegrationImpl implements DyIrsSyncIntegration {
    @Autowired
    private EduSyncIrsService eduSyncIrsService;
    @Autowired
    private DygxIntegration dygxIntegration;
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private CommonIntegration commonIntegration;
    @Value("${system.config.irs.send.flag:false}")
    private Boolean irsSendFlag;
    private final static String irsConnectionKey="irs:connection:flag";
    @Override
    @OpApi(funcCode = "IRS330783001", title = "本地irs平台数据发送到省irs平台", funcType = FuncTypeEnum.edit,publicFlag = BoolEnum.TRUE,savelog = false)
    public void sendIrsTaskData(AreaControlVO vo) {
        String redisKey= EduCache.EDU_BATCH_handle+"getIrs:"+(StringUtils.isBlank(vo.getSyncType())?"all":vo.getSyncType());
        if(redisHelper.hasKey(redisKey)){
            throw new AppException("正在获取中...");
        }
        Boolean canSend=false;
        if(redisHelper.hasKey(irsConnectionKey)){
            if((Boolean) redisHelper.get(irsConnectionKey)){
                canSend=true;
            }
        }else{
            canSend=true;
        }
        if(!canSend){
            return ;
        }
        PageHelper.startPage(1,500);
        QueryWrapper<EduSyncIrs> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncIrs::getSendFlag,BoolEnum.TRUE.getType())
                .eq(EduSyncIrs::getNewFlag,BoolEnum.TRUE.getType())
                .eq(EduSyncIrs::getIrsSendFlag,BoolEnum.FALSE.getType())
                .eq(StringUtils.isNotBlank(vo.getIrsCode()),EduSyncIrs::getIrsCode,vo.getIrsCode())
                .eq(StringUtils.isNotBlank(vo.getSyncType()),EduSyncIrs::getSyncType,vo.getSyncType())
                .orderByAsc(EduSyncIrs::getReqTime,EduSyncIrs::getSendTime);
        List<EduSyncIrs> list=eduSyncIrsService.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return;
        }

        PageInfo<EduSyncIrs> pageInfo=new PageInfo<>(list);
        redisHelper.set(irsConnectionKey,true,600);
        redisHelper.set(redisKey,"irs发送正在执行中",1800);
        for(EduSyncIrs eduSyncIrs:pageInfo.getList()){
            Boolean flag=true;
            if("IRSGX0003".equalsIgnoreCase(eduSyncIrs.getIrsCode())){
                flag=sendIRSGX0003(eduSyncIrs);
            }
            if ("IRSGX0004".equalsIgnoreCase(eduSyncIrs.getIrsCode())) {
                flag = sendIRSGX0004(eduSyncIrs);
            }
            if ("IRSGX0005".equalsIgnoreCase(eduSyncIrs.getIrsCode())) {
                flag = sendIRSGX0005(eduSyncIrs);
            }
            if(!flag){
                break;
            }
        }
        redisHelper.del(redisKey);
    }

    @Override
    @OpApi(funcCode = "IRS330783003", title = "本地irs平台数据发送到省irs平台错误数据重新发送", funcType = FuncTypeEnum.edit,publicFlag = BoolEnum.TRUE,savelog = false)
    public void sendIrsErrTaskData(AreaControlVO vo) {
        String redisKey= EduCache.EDU_BATCH_handle+"getErrIrs:"+(StringUtils.isBlank(vo.getSyncType())?"all":vo.getSyncType());
        if(redisHelper.hasKey(redisKey)){
            throw new AppException("正在获取中...");
        }
        Boolean canSend=false;
        if(redisHelper.hasKey(irsConnectionKey)){
            if((Boolean) redisHelper.get(irsConnectionKey)){
                canSend=true;
            }
        }else{
            canSend=true;
        }
        if(!canSend){
            return ;
        }
        QueryWrapper<EduSyncIrs> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncIrs::getSendFlag,BoolEnum.TRUE.getType())
                .eq(EduSyncIrs::getNewFlag,BoolEnum.TRUE.getType())
                .eq(EduSyncIrs::getIrsSendFlag,"2")
                .lt(EduSyncIrs::getIrsSendErrorCnt,3)
                .eq(StringUtils.isNotBlank(vo.getIrsCode()),EduSyncIrs::getIrsCode,vo.getIrsCode())
                .eq(StringUtils.isNotBlank(vo.getSyncType()),EduSyncIrs::getSyncType,vo.getSyncType())
                .orderByAsc(EduSyncIrs::getReqTime,EduSyncIrs::getSendTime);
        PageHelper.startPage(1,500);
        List<EduSyncIrs> list=eduSyncIrsService.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        PageInfo<EduSyncIrs> pageInfo=new PageInfo<>(list);
        redisHelper.set(irsConnectionKey,true,600);
        redisHelper.set(redisKey,"irs发送正在执行中",1800);
        for(EduSyncIrs eduSyncIrs:pageInfo.getList()){
            Boolean flag=true;
            if("IRSGX0003".equalsIgnoreCase(eduSyncIrs.getIrsCode())){
                flag=sendIRSGX0003(eduSyncIrs);
            }
            if ("IRSGX0004".equalsIgnoreCase(eduSyncIrs.getIrsCode())) {
                flag = sendIRSGX0004(eduSyncIrs);
            }
            if ("IRSGX0005".equalsIgnoreCase(eduSyncIrs.getIrsCode())) {
                flag = sendIRSGX0005(eduSyncIrs);
            }
            if(!flag){
                break;
            }
        }
        redisHelper.del(redisKey);
    }

    @Override
    @OpApi(funcCode = "IRS330783002", title = "重置东阳教育irs转发平台发送错误数据", funcType = FuncTypeEnum.edit,publicFlag = BoolEnum.TRUE,savelog = false)
    public void resetSendError(AreaControlVO vo) {
        if(irsSendFlag){
            UpdateWrapper<EduSyncIrs> updateWrapper=new UpdateWrapper<>();
            updateWrapper.lambda().set(EduSyncIrs::getIrsSendFlag,BoolEnum.FALSE.getType()).set(EduSyncIrs::getIrsSendErrorCnt,0).eq(EduSyncIrs::getIrsSendFlag,"2")
                    .eq(StringUtils.isNotBlank(vo.getIrsCode()),EduSyncIrs::getIrsCode,vo.getIrsCode())
                    .eq(StringUtils.isNotBlank(vo.getSyncType()),EduSyncIrs::getSyncType,vo.getSyncType());
            eduSyncIrsService.update(updateWrapper);
        }else{
            //调用发送接口
            if(StringUtils.isBlank(vo.getAreaCode())){
                vo.setAreaCode(SessionUtil.getAreaCode());
            }
            if(StringUtils.isBlank(vo.getAreaCode())){
                vo.setAreaCode(eduHelper.thisAreaCode());
            }
            CommonVO commonSendVO = new CommonVO();
            commonSendVO.setParamKey("IRS_LOCAL0004");
            commonSendVO.setAreaCode(vo.getAreaCode());
            String sendUrl = commonIntegration.getValueByKeyAndArea(commonSendVO);
            if (StringUtils.isBlank(sendUrl)) {
                throw new AppException("请先在系统参数表中设置IRS_LOCAL0004（重置本地irs平台发送错误数据）");
            }
            try {
                String body= HttpUtil.post(sendUrl, JSON.toJSONString(vo),2000);
            }catch (Exception e){
                throw new AppException("调用异常：网络不通");
            }
        }

    }

    @Override
    @OpApi(funcCode = "IRS330783004", title = "东阳教育irs转发平台发送缓存清除", funcType = FuncTypeEnum.edit,publicFlag = BoolEnum.TRUE,savelog = false)
    public void clearSendCache(AreaControlVO vo) {
        if(irsSendFlag){
            if(StringUtils.isBlank(vo.getAreaCode())){
                vo.setAreaCode(SessionUtil.getAreaCode());
            }
            if(StringUtils.isBlank(vo.getAreaCode())){
                vo.setAreaCode(eduHelper.thisAreaCode());
            }
            CommonVO commonSendVO = new CommonVO();
            commonSendVO.setParamKey("IRS_LOCAL0008");
            commonSendVO.setAreaCode(vo.getAreaCode());
            String sendUrl = commonIntegration.getValueByKeyAndArea(commonSendVO);
            if (StringUtils.isBlank(sendUrl)) {
                throw new AppException("请先在系统参数表中设置IRS_LOCAL0008（清除本地irs平台发送缓存）");
            }
            try {
                String body= HttpUtil.post(sendUrl, JSON.toJSONString(vo),2000);
            }catch (Exception e){
                throw new AppException("调用异常：网络不通");
            }
        }else{
            String redisKey= EduCache.EDU_BATCH_handle+"getIrs:"+(StringUtils.isBlank(vo.getSyncType())?"all":vo.getSyncType());
            redisHelper.del(redisKey);
        }

    }

    //省大数据共享IRS-省公安厅居民户口簿(家庭)
    private boolean sendIRSGX0003(EduSyncIrs eduSyncIrs){
        Boolean canSend=false;
        if(redisHelper.hasKey(irsConnectionKey)){
            if((Boolean) redisHelper.get(irsConnectionKey)){
                canSend=true;
            }
        }else{
            canSend=true;
        }
        if(!canSend){
            return false;
        }
        if(!"IRSGX0003".equalsIgnoreCase(eduSyncIrs.getIrsCode())){
            return true;
        }
        if(StringUtils.isNotBlank(eduSyncIrs.getReqParams())){
            HouseHoldSaveVO houseHoldSaveVO = JSON.parseObject(eduSyncIrs.getReqParams(),HouseHoldSaveVO.class);
            eduSyncIrs.setIrsSendTime(new Date());
            try {
                JSONArray jsonArray = dygxIntegration.getFamilyInfoIrs(houseHoldSaveVO.getIdcard(),houseHoldSaveVO.getReqIp());
                eduSyncIrs.setIrsSendFlag(BoolEnum.TRUE.getType());
                eduSyncIrs.setIrsSendMsg("成功");
                eduSyncIrs.setResParams(JSON.toJSONString(jsonArray));
                eduSyncIrs.setResTime(new Date());
            } catch (AppException e){
                eduSyncIrs.setIrsSendFlag("2");
                if(StringUtils.isNotBlank(e.getMsg())&&e.getMsg().length()>300){
                    eduSyncIrs.setIrsSendMsg(e.getMsg().substring(0,200));
                }else{
                    eduSyncIrs.setIrsSendMsg(e.getMsg());
                }
                eduSyncIrs.setIrsSendErrorCnt(eduSyncIrs.getIrsSendErrorCnt()==null?1:eduSyncIrs.getIrsSendErrorCnt()+1);
            } catch (IORuntimeException e){
                redisHelper.set(irsConnectionKey,false,300);
                eduSyncIrs.setIrsSendMsg("网络异常");
                eduSyncIrsService.updateById(eduSyncIrs);
                return false;
            }catch (Exception e){
                eduSyncIrs.setIrsSendFlag("2");
                if(StringUtils.isNotBlank(e.getMessage())&&e.getMessage().length()>300){
                    eduSyncIrs.setIrsSendMsg("发送省irs平台失败："+e.getMessage().substring(0,200));
                }else {
                    eduSyncIrs.setIrsSendMsg("发送省irs平台失败：" + e.getMessage());
                }
                eduSyncIrs.setIrsSendErrorCnt(eduSyncIrs.getIrsSendErrorCnt()==null?1:eduSyncIrs.getIrsSendErrorCnt()+1);
            }

        }
        eduSyncIrs.setSendFlag(BoolEnum.TRUE.getType());
        eduSyncIrsService.updateById(eduSyncIrs);
        return true;
    }

    //省大数据共享IRS-法人企业信息查询
    private boolean sendIRSGX0004(EduSyncIrs eduSyncIrs) {
        Boolean canSend = false;
        if (redisHelper.hasKey(irsConnectionKey)) {
            if ((Boolean) redisHelper.get(irsConnectionKey)) {
                canSend = true;
            }
        } else {
            canSend = true;
        }
        if (!canSend) {
            return false;
        }
        if (!"IRSGX0004".equalsIgnoreCase(eduSyncIrs.getIrsCode())) {
            return true;
        }
        if (StringUtils.isNotBlank(eduSyncIrs.getReqParams())) {
            QySaveVO qySaveVO = JSON.parseObject(eduSyncIrs.getReqParams(), QySaveVO.class);
            eduSyncIrs.setIrsSendTime(new Date());
            try {
                JSONArray jsonArray = dygxIntegration.getFrQyIrs(qySaveVO.getIdcard());
                eduSyncIrs.setIrsSendFlag(BoolEnum.TRUE.getType());
                eduSyncIrs.setIrsSendMsg("成功");
                eduSyncIrs.setResParams(JSON.toJSONString(jsonArray));
                eduSyncIrs.setResTime(new Date());
            } catch (AppException e) {
                eduSyncIrs.setIrsSendFlag("2");
                if (StringUtils.isNotBlank(e.getMsg()) && e.getMsg().length() > 300) {
                    eduSyncIrs.setIrsSendMsg(e.getMsg().substring(0, 200));
                } else {
                    eduSyncIrs.setIrsSendMsg(e.getMsg());
                }
                eduSyncIrs.setIrsSendErrorCnt(eduSyncIrs.getIrsSendErrorCnt() == null ? 1 : eduSyncIrs.getIrsSendErrorCnt() + 1);
            } catch (IORuntimeException e) {
                redisHelper.set(irsConnectionKey, false, 300);
                eduSyncIrs.setIrsSendMsg("网络异常");
                eduSyncIrsService.updateById(eduSyncIrs);
                return false;
            } catch (Exception e) {
                eduSyncIrs.setIrsSendFlag("2");
                if (StringUtils.isNotBlank(e.getMessage()) && e.getMessage().length() > 300) {
                    eduSyncIrs.setIrsSendMsg("发送省irs平台失败：" + e.getMessage().substring(0, 200));
                } else {
                    eduSyncIrs.setIrsSendMsg("发送省irs平台失败：" + e.getMessage());
                }
                eduSyncIrs.setIrsSendErrorCnt(eduSyncIrs.getIrsSendErrorCnt() == null ? 1 : eduSyncIrs.getIrsSendErrorCnt() + 1);
            }

        }
        eduSyncIrs.setSendFlag(BoolEnum.TRUE.getType());
        eduSyncIrsService.updateById(eduSyncIrs);
        return true;
    }

    //省大数据共享IRS-省公安厅居住证
    private boolean sendIRSGX0005(EduSyncIrs eduSyncIrs) {
        Boolean canSend = false;
        if (redisHelper.hasKey(irsConnectionKey)) {
            if ((Boolean) redisHelper.get(irsConnectionKey)) {
                canSend = true;
            }
        } else {
            canSend = true;
        }
        if (!canSend) {
            return false;
        }
        if (!"IRSGX0005".equalsIgnoreCase(eduSyncIrs.getIrsCode())) {
            return true;
        }
        if (StringUtils.isNotBlank(eduSyncIrs.getReqParams())) {
            JzzSaveVO jzzSaveVO = JSON.parseObject(eduSyncIrs.getReqParams(), JzzSaveVO.class);
            eduSyncIrs.setIrsSendTime(new Date());
            try {
                JSONArray jsonArray = dygxIntegration.getJzzIrs(jzzSaveVO.getIdcard(), jzzSaveVO.getName(),jzzSaveVO.getReqIp());
                eduSyncIrs.setIrsSendFlag(BoolEnum.TRUE.getType());
                eduSyncIrs.setIrsSendMsg("成功");
                eduSyncIrs.setResParams(JSON.toJSONString(jsonArray));
                eduSyncIrs.setResTime(new Date());
            } catch (AppException e) {
                eduSyncIrs.setIrsSendFlag("2");
                if (StringUtils.isNotBlank(e.getMsg()) && e.getMsg().length() > 300) {
                    eduSyncIrs.setIrsSendMsg(e.getMsg().substring(0, 200));
                } else {
                    eduSyncIrs.setIrsSendMsg(e.getMsg());
                }
                eduSyncIrs.setIrsSendErrorCnt(eduSyncIrs.getIrsSendErrorCnt() == null ? 1 : eduSyncIrs.getIrsSendErrorCnt() + 1);
            } catch (IORuntimeException e) {
                redisHelper.set(irsConnectionKey, false, 300);
                eduSyncIrs.setIrsSendMsg("网络异常");
                eduSyncIrsService.updateById(eduSyncIrs);
                return false;
            } catch (Exception e) {
                eduSyncIrs.setIrsSendFlag("2");
                if (StringUtils.isNotBlank(e.getMessage()) && e.getMessage().length() > 300) {
                    eduSyncIrs.setIrsSendMsg("发送省irs平台失败：" + e.getMessage().substring(0, 200));
                } else {
                    eduSyncIrs.setIrsSendMsg("发送省irs平台失败：" + e.getMessage());
                }
                eduSyncIrs.setIrsSendErrorCnt(eduSyncIrs.getIrsSendErrorCnt() == null ? 1 : eduSyncIrs.getIrsSendErrorCnt() + 1);
            }

        }
        eduSyncIrs.setSendFlag(BoolEnum.TRUE.getType());
        eduSyncIrsService.updateById(eduSyncIrs);
        return true;
    }
}
